package cc.rengu.redp.flowable.service.modelValidator;

import cc.rengu.redp.flowable.domain.CustomUserNode;
import com.alibaba.fastjson.JSON;
import org.apache.commons.lang3.StringUtils;
import org.flowable.bpmn.model.BpmnModel;
import org.flowable.bpmn.model.Process;
import org.flowable.bpmn.model.UserTask;
import org.flowable.validation.ValidationError;
import org.flowable.validation.validator.ProcessLevelValidator;

import java.util.List;

public class CustomUserNodeValidator extends ProcessLevelValidator {
    @Override
    protected void executeValidation(BpmnModel bpmnModel, Process process, List<ValidationError> list) {
        List<UserTask> userTasks = process.findFlowElementsOfType(UserTask.class);

        for (UserTask userTask : userTasks) {
            CustomUserNode customUserNode = JSON.parseObject(userTask.getDocumentation(), CustomUserNode.class);
            if (customUserNode != null) {
                if (
                        StringUtils.isBlank(customUserNode.getFormTitle()) ||
                                StringUtils.isBlank(customUserNode.getFormType()) ||
                                (StringUtils.isBlank(customUserNode.getFormId()) && StringUtils.isBlank(customUserNode.getFormPath()))
                ) {
                    list.add(GenValidateError.get(userTask.getId(), userTask.getName(), "用户节点表单关联信息不完整", true));
                }
            }

            List<String> users = userTask.getCandidateUsers();
            List<String> groups = userTask.getCandidateGroups();
            if (customUserNode.isSetAssignToApplicant() == false) {
                if ((users == null || users.isEmpty()) &&
                        (groups == null || groups.isEmpty()) &&
                        StringUtils.isBlank(userTask.getAssignee())) {
                    list.add(GenValidateError.get(userTask.getId(), userTask.getName(), "用户节点未绑定权限参数", true));
                }
            }
        }
    }
}
